import Rect from './rect'

const image = new Image()
image.src = 'images/target.png'

const disImage = new Image()
disImage.src = 'images/block0.png'

export default class Button extends Rect {
    constructor(startx, starty, width, height, text) {
        super(startx, starty, width, height)
        this.text = text
        this.foreColor = '#e5c2a7'
        this.font = '18px Arial bold'
    }
    /**
     * 背景图重绘函数
     * 绘制两张图片
     */
    render(ctx) {
        let img = image
        if (this.disabled) {
            img = disImage
        }
        ctx.drawImage(
            img,
            0, 0, 70, 35,
            this.startx,
            this.starty,
            this.width,
            this.height
        )
        ctx.fillStyle = this.foreColor
        ctx.font = this.font

        let textw = this.text.length * 18
        let left = (this.width - textw) / 2

        ctx.fillText(this.text, this.startx + left, this.starty + 27)
    }

    click(x, y) {
        if (this.disabled) {
            return false
        }
        if (this.contains(x, y)) {
            this.handler && this.handler()
            return true
        }
        return false
    }

    onclick(handler) {
        this.handler = handler
    }
}